<?php
namespace app\api\controller\Orderhawa;

use app\api\controller\Base;
use app\api\controller\mytool\Sendmessage;
use app\common\model\buss\Buss;
use app\common\model\company\Company;
use app\common\model\orderhawa\HawaList;
use app\common\model\power\Rolepower;
use app\common\model\power\Rolepowerlnk;
use app\common\model\transit\Transitcompany;
use app\common\model\transit\TransitDriver;
use app\common\model\transit\Transport;
use app\common\model\user\User as UserModel;
use think\facade\Env;
use think\File;

class Manaorderhawa extends Base
{
    /**
     * 产生jwt加密串，参考session
     */
    public function initialize()
    {
        parent::initialize();
        self::is_login();
        Rolepower::powerguard(204003);
    }

    /**
     * 查看订单信息
     * @return [type] [description]
     */
    public function getinfo()
    {
        $id = input('id');
        if (empty($id)) {
            return myerr('缺少参数，请重新尝试');
        }
        $data = HawaList::getinfo($id, 'mana');
        if (!$data['code']) {
            return myerr($data['msg']);
        }
        $data                   = $data['msg'];
        $data['companyinfo']    = Company::user_getinfo($data['CompanyId']);
        $data['hawa']           = UserModel::getpublicinfo($data['UpUserId']);
        $data['power']          = Rolepowerlnk::getpowerlnk('orderhawa');
        $data['busslist']       = Buss::getoklist(['UserId', 'UserName', 'CardNumber', 'CarNumber', 'UserTel', 'UserImg', 'CarImg', 'Address']);
        $sdata['order']         = 'TransitCompanyId desc';
        $data['TransitCompany'] = Transitcompany::usergetlist($sdata, 'mana', false);
        $data['TranSport']      = Transport::usergetlist($sdata, 'buss', false);
        $data['TransitDriver']  = TransitDriver::usergetlist($sdata, 'buss', false);

        $data['CELLPHONE'] = CELLPHONE;
        $data['goodsbox']  = GOODSBOX;
        //服务费信息
        if(get_config_value('switch_Rebate')){
            $rebate = new RebateList();
            $data['rebate'] = $rebate->get_view_info($id,'orderhawa');
        }
        return myok($data);
    }

    /**
     * 修改/完善企业信息
     * 产废人信息也再次完善
     * @return [type] [description]
     */
    function list() {
        $data = input('get.');
        $data = init_where($data);
        $list = HawaList::usergetlist($data, 'mana');
        foreach ($list['list'] as $key => $value) {
            if (empty($value['companyinfo']['Name'])) {
                $list['list'][$key]['Name'] = '暂未完善名称';
            } else {
                $list['list'][$key]['Name'] = $value['companyinfo']['Name'];
            }
            if (empty($value['tranuserinfo'])) {
                if (empty($value['bussinfo']['UserName'])) {
                    $list['list'][$key]['BussName'] = '暂无';
                } else {
                    $list['list'][$key]['BussName'] = '业：'.$value['bussinfo']['UserName'];
                }
            } else {
                $list['list'][$key]['BussName'] =  '收：'.$value['tranuserinfo']['Name'];
            }
        }
        $list['tr']['title'] = ['产废单位', '下单时间', '订单状态', '查看', '收集员', '装车时间', '结算时间', '订单费用'];
        $list['tr']['key']   = ['Name', 'UpTime', 'State', 'HawaListId', 'BussName', 'LoadingTime', 'SettlementTime', 'TotalCost'];
        $list['tr']['show']  = [true, true, true, true, true, false, false, false];
        return myok($list);

    }

    /**
     * 地图查看订单（分配使用）
     * @return [type] [description]
     */
    public function maplist()
    {
        $data          = input('post.');
        $data['state'] = empty($data['state']) ? 0 : $data['state'];
        $list          = HawaList::Managetlist($data, $data['state']);
        foreach ($list['list'] as $key => $value) {
            if (!empty($value['companyinfo'])) {
                $list['list'][$key] = array_merge($list['list'][$key], $value['companyinfo']);
            }
            if (empty($list['list'][$key]['Name'])) {
                $list['list'][$key]['Name'] = '暂未完善名称';
            }
        }
        $list['tr']['title'] = ['产废单位', '下单时间', '订单状态', '查看'];
        $list['tr']['key']   = ['Name', 'UpTime', 'State', 'HawaListId'];
        $list['buss']        = Buss::getoklist(['UserName', 'Address', 'UserTel', 'UserId']);
        $sdata['order']      = 'TransitCompanyId desc';
        $list['tran']        = Transitcompany::usergetlist($sdata, 'mana', false);
        return myok($list);
    }

    /**
     * 订单分配
     * @return [type] [description]
     */
    public function dist()
    {
        $data  = init_post(input('post.'));
        $udata = $data;
        $sb    = HawaList::test_state($data['ids'], HawaList::STATEINT);
        if (!$sb) {
            return myerr('数据异常，请重新尝试');
        }
        if (empty($data['groupid']) || empty($data['bussid'])) {
            return myerr('请选择分配对象');
        }
        $gid = (Int) $data['groupid'];
        if ($gid !== 1 && $gid !== 2 && $gid !== 3) {
            return myerr('分配组错误');
        }
        $data = HawaList::dist($data);
        foreach ($udata['ids'] as $key => $value) {
            $sb = Sendmessage::Orderhawa(2, $value);
        }
        if (!$sb['code']) {
            return myok($data['msg'] . '，请通知收集员');
        }
        return myok($data['msg']);
    }
    /**
     * 变更收集员
     * @return [type] [description]
     */
    public function changebuss()
    {
        $data = input('post.');
        $sb   = HawaList::changedist($data);
        Sendmessage::Orderhawa(2, $data['id']);
        return myok($sb['msg']);
    }
    /**
     * 变更运输公司
     * @return [type] [description]
     */
    public function changetran()
    {
        $data = input('post.');
        $sb   = HawaList::changetran($data);
        Sendmessage::Orderhawa(2, $data['id']);
        return myok($sb['msg']);
    }
    /**
     * 变更浮差
     * @return [type] [description]
     */
    public function changeprice()
    {
        Rolepower::powerguard(205002);
        $id   = input('id');
        $data = HawaList::liststate($id);
        if (empty($data)) {
            return myerr('没有找到需要的订单');
        }
        $data        = $data['msg'];
        $rdata       = [];
        $rdata['id'] = $id;
        if (!empty(input('FloatingCost'))) {
            $rdata['FloatingCost'] = input('FloatingCost');
        }
        if (!empty(input('FloatingNote'))) {
            $rdata['FloatingNote'] = input('FloatingNote');
        }
        if (!empty($data['FloatingCost'])) {
            $data['TotalCost'] = $data['TotalCost'] - $data['FloatingCost'];
        }
        $rdata['TotalCost'] = $data['TotalCost'] + $rdata['FloatingCost'];
        HawaList::user_reinfo($rdata);
        //检查结算账单是否一致
        if (!empty($data['SettlementTime'])) {
            //会计已经结算，但是修改了价格
            return myok('修改成功，已通知会计价格变动');
        } else {
            return myok('修改成功');
        }
    }
    /**
     * 删除订单
     * @return [type] [description]
     */
    public function deleteorderlist(){
        $id   = input('id');
        if(empty($id)){
            return myerr('缺少数据');
        }
        $data = HawaList::deleteorderlist($id);
        return myok('删除成功');
    }

    /**
     * 图片上传
     * @return [type] [description]
     */
    public function upimg()
    {
        $type = empty(input('type')) ? 'other' : input('type');
        if (!$type == 'company' || !$type == 'user' || !$type == 'order') {
            $type = 'other';
        }
        try {
            $file = request()->file('img');
        } catch (\Exception $e) {
            return json_encode(['status' => 'error', 'data' => $e->getMessage()]);
        }
        // 移动到框架应用根目录/public/uploads/ 目录下
        if (!is_null($file)) {
            try {
                $save_path = Env::get('root_path') . 'public\\static' . '\\upimg\\hawa\\' . $type . '\\';
                $info      = $file->validate(["size" => 50000000, 'ext' => 'jpg,png,gif'])->rule("date")->move($save_path);
                //echo $save_path. DS . date("Ymd") . DS .  $info->getFilename();
                $image = \think\Image::open($save_path . '\\' . $info->getSaveName());
                $image->thumb(2000, 2000)->save($save_path . '\\' . $info->getSaveName());
                if ($info) {
//getSaveName();
                    $p = $info->getFilename();
                    return json_encode(['status' => 'ok', 'data' => SERVERURL . 'static/upimg/hawa/' . $type . '/' . date('Ymd', time()) . '/' . $p]);
                } else {
                    return json_encode(['status' => 'error', 'data' => $info->getError()]);
                }
            } catch (\Exception $e) {
                return json_encode(['status' => 'error', 'data' => $e->getMessage()]);
            }

        } else {
            return json_encode(['status' => 'error', 'data' => '没有找到需要上传的图片']);
        }
    }

    /**
     * 判断账号是否登录
     * @return boolean [description]
     */
    private function is_login()
    {
        $data = UserModel::is_sessionlogin();
        if (!$data['code']) {
            $data['options'] = 'relogin';
            json($data)->send();
            exit;
        }
    }
}
